package com.sicent.operate.web.interceptor;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.sicent.operate.common.util.CookieUtils;
import com.sicent.operate.common.util.RedisUtils;


/*
 * session 超时拦截器
 */
public class SessionTimeoutInterceptor implements HandlerInterceptor {

	public String[] allowUrls;//还没发现可以直接配置不拦截的资源，所以在代码里面来排除

    @Autowired
    private ResourceBundleMessageSource resourceBundleMessageSource;
    
    public void setAllowUrls(String[] allowUrls) {
        this.allowUrls = allowUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception {
        String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");  
        if(null != allowUrls && allowUrls.length>=1)
            for(String url : allowUrls) {  
                if(requestUrl.contains(url)) {
                    return true;  
                }  
            }

        String login= CookieUtils.getCookie(request, CookieUtils.LONG_COOKIE);
        if(StringUtils.isNotBlank(login)) {
        	String info=RedisUtils.get(login);
            if(StringUtils.isNotBlank(info)){
            	//重新设置 cookie 时间 模拟session超时时间 ---30分钟不操作 session失效
            	RedisUtils.setAndExpire(login, info, 30*60);
            	return true;//返回true，则这个方面调用后会接着调用postHandle(),  afterCompletion()
            }else{
            	 throw new SessionTimeoutException();
            }
        }else{
        	 throw new SessionTimeoutException();
        }
    }
    
    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
    }
    
    protected String getMessage(HttpServletRequest request, String code, Object... args) {
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        Locale locale = localeResolver.resolveLocale(request);

        return resourceBundleMessageSource.getMessage(code, args, locale);
    }

	
	
}
